/*	$Id: if.c 6 2008-07-29 02:30:10Z phrakt $	*/
/*
 * Copyright (c) 2003 Jean-Francois Brousseau <jfb@openbsd.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Network interface layering code
 *
 * The functions in here gather information on the network interfaces
 * available on the running system, and store the information in a list of
 * system-independent structures.  The code in this file is getting somewhat
 * hairy due to all the tricks we have to do to gather information, since
 * there are about a million different ways to get to it, but none is really
 * portable.
 *
 * Before making any modifications in here, make sure to test on all supported
 * platforms to avoid breaking functionality.
 */

#include <sys/param.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/socket.h>

#include <net/if.h>

#if defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/if_media.h>

#include <ifaddrs.h>

#elif defined(__linux__)
#include <net/if_arp.h>
#endif

#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#include "if.h"
#include "dlink.h"
#include "queue.h"
#include "pforge.h"
#include "private.h"


#define PFIF_NBIF_INIT  24
#define PFIF_NBIF_INCR  10



extern struct pf_netif_ops pf_loop_ops;
extern struct pf_netif_ops pf_ether_ops;


static int       pf_netif_xlateflags (int);


static const struct pf_netif_type {
	char   ift_desc[32];
	struct pf_netif_ops *ift_opv;
} pf_netif_types[] = {
	{ "",                     NULL },
	{ "other",                NULL },
	{ "X25 to IMP",           NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Ethernet",             &pf_ether_ops },
	{ "",                     NULL },
	{ "Token Bus",            NULL },
	{ "Token Ring",           NULL },
	{ "",                     NULL },	/* 10 */
	{ "StarLAN",              NULL },
	{ "Proteon 10Mb ring",    NULL },
	{ "Proteon 80Mb ring",    NULL },
	{ "Hyperchannel",         NULL },
	{ "FDDI",                 NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Basic ISDN",           NULL },	/* 20 */
	{ "Primary ISDN",         NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Loopback",             &pf_loop_ops },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 30 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "RS-232",               NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "ATM",                  NULL },
	{ "",                     NULL },
	{ "SONET",                NULL },
	{ "",                     NULL },	/* 40 */
	{ "",                     NULL },
	{ "Localtalk",            NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Modem",                NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 50 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 60 */
	{ "",                     NULL },
	{ "Fast Ethernet",        NULL },
	{ "ISDN",                 NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 70 */
	{ "IEEE 802.11",          NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 80 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },	/* 90 */
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "",                     NULL },
	{ "Myrinet",              NULL },
	{ "",                     NULL },	/* 100 */
};

#define NB_IFTYPES   (sizeof(pf_netif_types)/sizeof(struct pf_netif_type))


/* flag translation table */
static const int pf_netif_fltab[32] = {
	PFIF_FL_UP,
	PFIF_FL_BCAST,
	0,
	PFIF_FL_LOOPBACK,
	PFIF_FL_PTP,
	0,
	0,
	0,
	PFIF_FL_PROMISC,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
	0,
};


/* global interface table */
static PF_NETIF        *pf_netif_tab[PFIF_MAXIF];
#ifdef PF_THREAD_SAFE
static pthread_mutex_t  pf_netif_mtx = PTHREAD_MUTEX_INITIALIZER;
#endif


/*
 * pf_netif_init()
 *
 */
int
pf_netif_init(void)
{
	int ret;
	PF_NETIF *ifp;

#ifdef PF_THREAD_SAFE
	ret = pthread_mutex_init(&pf_netif_mtx, NULL);
	if (ret != 0) {
		return (-1);
	}
#endif

	return (0);
}


/*
 * pf_netif_cleanup()
 *
 */
void
pf_netif_cleanup(void)
{
	int i;

	for (i = 0; i < PFIF_MAXIF; i++) {
		if (pf_netif_tab[i] == NULL)
			continue;

		pf_netif_free(pf_netif_tab[i]);
		pf_netif_tab[i] = NULL;
	}

#ifdef PF_THREAD_SAFE
	(void)pthread_mutex_destroy(&pf_netif_mtx);
	pf_netif_mtx = PTHREAD_MUTEX_INITIALIZER;
#endif
}

/*
 * pf_netif_create()
 *
 * Create a new network interface of type <type> and with name <name>.
 * Returns the new interface's index on success, or -1 on failure.
 */
int
pf_netif_create(int type, const char *name, int flags)
{
	struct ifreq ifr;
	PF_NETIF *ifp;

	/* do we support this interface type */
	if (type > (int)NB_IFTYPES) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_types[type].ift_opv == NULL) {
		pf_seterr(PF_ERR_NOTSUP);
		return (-1);
	}

	if ((ifp = pf_netif_alloc()) == NULL)
		return (-1);

	ifp->if_type = type;
	ifp->if_flags = flags & ~PFIF_INT_FLAGS;
	strlcpy(ifp->if_name, name, sizeof(ifp->if_name));

	if (pf_netif_add(ifp, -1) < 0)
		return (-1);

	if ((pf_netif_types[type].ift_opv->if_create != NULL) &&
	    (pf_netif_types[type].ift_opv->if_create(ifp) < 0)) {
		pf_netif_tab[ifp->if_index] = NULL;
		pf_netif_free(ifp);
		return (-1);
	}

	return (ifp->if_index);
}

/*
 * pf_netif_delete()
 *
 * Delete the network interface whose index is given in <nid>.
 * Returns 0 on success, or -1 on failure.
 */
int
pf_netif_delete(int nid)
{
	int ret;
	PF_NETIF *ifp;

	if ((nid < 0) || (nid > PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_tab[nid] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

#ifdef PF_THREAD_SAFE
	if ((ret = pthread_mutex_lock(&pf_netif_mtx)) != 0) {
		return (-1);
	}
#endif
	ifp = pf_netif_tab[nid];

	if ((pf_netif_types[ifp->if_type].ift_opv->if_delete != NULL) &&
	    (pf_netif_types[ifp->if_type].ift_opv->if_delete(ifp) < 0))
		return (-1);

	pf_netif_free(pf_netif_tab[nid]);
	pf_netif_tab[nid] = NULL;

#ifdef PF_THREAD_SAFE
	(void)pthread_mutex_unlock(&pf_netif_mtx);
#endif

	return (0);
}


/*
 * pf_netif_getinfo()
 *
 * Retrieve information on the network interface whose index is given in <id>.
 */
int
pf_netif_getinfo(int id, struct pf_netif_info *info)
{
	PF_NETIF *ifp;

	if ((id < 0) || (id >= PFIF_MAXIF))
		return (-1);

	if (pf_netif_tab[id] == NULL)
		return (-1);

	ifp = pf_netif_tab[id];

	strlcpy(info->ifi_name, ifp->if_name, sizeof(info->ifi_name));
	info->ifi_index = ifp->if_index;
	info->ifi_type = ifp->if_type;
	info->ifi_mtu = ifp->if_mtu;
	info->ifi_flags = ifp->if_flags;

	info->ifi_hwalen = ifp->if_hwalen;
	if (ifp->if_hwalen > 0)
		memcpy(info->ifi_hwaddr, ifp->if_hwaddr, ifp->if_hwalen);

	return (0);
}



/*
 * pf_netif_add()
 *
 * Add an interface <nif> to the interface table, at index <id>.  If the
 * entry at the requested index is already used, an error will be returned.
 * If the <id> argument is -1, the first available slot will be assigned to
 * the new interface.
 * Returns 0 on success, or -1 on failure.
 */
int
pf_netif_add(PF_NETIF *nif, int id)
{
	int ret;

#ifdef PF_THREAD_SAFE
	ret = pthread_mutex_lock(&pf_netif_mtx);
	if (ret != 0) {
		return (-1);
	}
#endif

	if (id == -1) {
		for (id = 0; id < PFIF_MAXIF; id++)
			if (pf_netif_tab[id] == NULL)
				break;
		if (id == PFIF_MAXIF)
			return (-1);
	} else if (pf_netif_tab[id] != NULL)
		return (-1);

	pf_netif_tab[id] = nif;

#ifdef PF_THREAD_SAFE
	(void)pthread_mutex_unlock(&pf_netif_mtx);
#endif
	return (id);
}



/*
 * pf_netif_getindex()
 *
 * Returns the index of the interface whose name matches <ifname>, or -1 if
 * there is no such interface.
 */
int
pf_netif_getindex(const char *ifname)
{
	int i, id;

	id = -1;
	for (i = 0; i < PFIF_MAXIF; i++) {
		if ((pf_netif_tab[i] != NULL) &&
		    (strcmp(ifname, pf_netif_tab[i]->if_name) == 0)) {
			id = pf_netif_tab[i]->if_index;
			break;
		}
	}

	return (id);
}

/*
 * pf_netif_open()
 *
 * Open the interface for reading and writing by binding it to a datalink
 * device.
 * Returns 0 on success, or -1 on failure.
 */
int
pf_netif_open(int nid)
{
	int dltype;
	PF_NETIF *ifp;

	if ((nid < 0) || (nid >= PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_tab[nid] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	ifp = pf_netif_tab[nid];

	if (ifp->if_flags & PFIF_FL_VIRTUAL)
		dltype = PFDL_TYPE_PCAP;
	else
		dltype = PFDL_TYPE_ANY;

	ifp->if_dlink = pf_dlink_open(dltype);
	if (ifp->if_dlink == NULL)
		return (-1);

	if (pf_dlink_bind(ifp->if_dlink, ifp->if_index) < 0) {
		return (-1);
	}

	return (0);
}


/*
 * pf_netif_close()
 *
 * Close the network interface whose descriptor is given in <nid>.
 */
int
pf_netif_close(int nid)
{
	PF_NETIF *ifp;

	if ((nid < 0) || (nid >= PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (-1);
	} else if (pf_netif_tab[nid] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	ifp = pf_netif_tab[nid];

	if (ifp->if_dlink == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (-1);
	}

	pf_dlink_close(ifp->if_dlink);
	ifp->if_dlink = NULL;

	return (0);
}


/*
 * pf_netif_recvpkt()
 *
 * Read data currently available on the network interface and dispatch it
 * appropriately.
 */
PF_PKT*
pf_netif_recvpkt(int id)
{
	PF_PKT *pkt;
	PF_NETIF *ifp;

	if ((id < 0) || (id >= PFIF_MAXIF)) {
		pf_seterr(PF_ERR_RANGE);
		return (NULL);
	}
	else if (pf_netif_tab[id] == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (NULL);
	}

	ifp = pf_netif_tab[id];
	if (ifp->if_dlink == NULL) {
		pf_seterr(PF_ERR_INVARG);
		return (NULL);
	}

	pkt = pf_dlink_read(ifp->if_dlink);
	if (pkt == NULL)
		return (NULL);

	pkt->pkt_if = ifp->if_index;

	if ((pf_netif_types[ifp->if_type].ift_opv->if_input != NULL) &&
	    (pf_netif_types[ifp->if_type].ift_opv->if_input(ifp, pkt) < 0)) {
		return (NULL);
	}

	return (pkt);
}

/*
 * pf_netif_sendpkt()
 *
 */
int
pf_netif_sendpkt(int nid, PF_PKT *pkt)
{


	return (0);
}

/*
 * pf_netif_alloc()
 *
 * Allocate a new network interface (pfnet_if) structure and return it.
 */
PF_NETIF*
pf_netif_alloc(void)
{
	PF_NETIF *aif;

	aif = (PF_NETIF *)malloc(sizeof(*aif));
	if (aif != NULL) {
		memset(aif, 0, sizeof(*aif));
		aif->if_index = PFIF_INDEX_INVAL;
	}

	return (aif);
}


/*
 * pf_netif_free()
 *
 */
void
pf_netif_free(PF_NETIF *ifp)
{
	free(ifp);
}


static int
pf_netif_xlateflags(int flags)
{
	int i, ret = 0;

	for (i = 0; i < (int)(sizeof(flags) * 8); i++)
		if (flags & (1 << i))
			ret |= pf_netif_fltab[i];

	return (ret);
}
